package com.woniuxy.health.commodity.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.woniuxy.health.commodity.dto.MessageDTO;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author huang
 * @date 2023/9/13 10:31
 * 上架商品后把队列中的邮件消息进行发送
 */
@Component
@RabbitListener(queues = "GoodsUpLoadQueue")
public class UploadQueueListener {

    private final JavaMailSender javaMailSender;

    public UploadQueueListener(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    @RabbitHandler
    public void handler(String str, Channel channel, Message message, @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag) throws IOException {
        try {
            // 发送邮件
            MessageDTO messageDTO = JSONUtil.toBean(str, MessageDTO.class);
            SimpleMailMessage smm = BeanUtil.copyProperties(messageDTO, SimpleMailMessage.class);
            smm.setTo(messageDTO.getTo()[0]);
            javaMailSender.send(smm);
        } catch (Exception e) {
            channel.basicNack(deliveryTag, false, true);
        }
    }
}
